
var requestHandlers = require("./requestHandlers");

var handle = {};
handle["/status"] = requestHandlers.printStatus;
handle["/getResource"] = requestHandlers.getResource;
handle["/getJST"] = requestHandlers.getJST;


function routeForward(resourceMap, resource, res, req){


    

    if (typeof resourceMap[resource] === 'function') {


        try {

            //set a 1 second timer in case noone calls end()  
            res.setTimeOutTimer(res);

            resourceMap[resource](req, res);
           


        } catch (err) {


            res.status = 500;
            res.end();
        }



    }
    

}



function route(resourceMap, pathname, myResponse, myRequest, rootFolder, status) {

    


    if (pathname == "/status") {
        status.addSuccesfulCounter();

        handle["/status"](myResponse, myRequest, status);




    }


    //first try the dynamic function
    else if (typeof resourceMap[pathname] === 'function') {


        try {

            //set a 1 second timer in case noone calls end()  
            myResponse.setTimeOutTimer(myResponse);

            resourceMap[pathname](myRequest, myResponse);
            status.addSuccesfulCounter();


        } catch (err) {


            myResponse.status = 500;
            myResponse.end();
        }


        
    }else if(pathname.indexOf(".jst")!=-1){

        try {
             //get the jst file into the resourceMap
              handle["/getJST"](pathname,myResponse, myRequest, rootFolder, status);

       

         


        } catch (err) {


            myResponse.status = 500;
            myResponse.end();
        }

    
    }

    else {

        status.addStaticCounter();

        //Try the static way
        handle["/getResource"](myResponse, myRequest, rootFolder, status);







    }

}


exports.route = route;
exports.routeForward = routeForward;